package com.um.jdy.app.activity.manager;

import com.um.jdy.app.activity.entity.dto.CouponsGoodsPageDTO;
import com.um.jdy.app.shop.entity.dto.GoodsPageDTO;
import com.um.jdy.app.shop.entity.vo.GoodsItemVO;
import com.um.jdy.common.activity.code.CouponsCode;
import com.um.jdy.common.activity.entity.po.Coupons;
import com.um.jdy.common.activity.service.CouponsService;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.shop.enums.CouponsEnum;
import com.um.jdy.common.shop.service.GoodsService;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.utils.condition.ConditionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 管理类：优惠券站场关联表
 */
@Component
public class CouponsGoodsManager {

    @Autowired
    CouponsService couponsService;

    @Autowired
    GoodsService goodsService;

    /**
     * 分页查询商品
     * @param dto
     * @return
     */
    public Page<GoodsItemVO> getGoodsPage(CouponsGoodsPageDTO dto){
        Coupons coupons = couponsService.getEntity(dto.getActivityCouponsId());
        if(null == coupons){
            throw new ServiceException(CouponsCode.CouponsNotExist);
        }

        Page page = new Page(dto);

        ConditionBuilder conditionBuilder = ConditionBuilder.create()
                .put("g.code", dto.getCode())
                .put("g.com_id",couponsService.getComId())
                .putLike("g.shop_goods_name", dto.getShopGoodsName());

        if(CouponsEnum.AvailableType.Part.name().equals(coupons.getAvailable())) {
            conditionBuilder.putLike("c.activity_coupons_ids", coupons.getActivityCouponsId());
        }
        if(YesOrNo.No.name().equals(coupons.getIsActivityMerge())) {
            conditionBuilder.put("a.activity_type", null, true);
        }

        Map<String, String> condition = conditionBuilder.build();

        List<GoodsPageDTO.Sort> sorts = Optional.ofNullable(dto.getSorts()).orElseGet(() -> new ArrayList());
        String[] filed = sorts.stream().map(item -> item.getFiled().getValue()).toArray(String[]::new);
        String[] sort = sorts.stream().map(item -> item.getOrder().name()).toArray(String[]::new);
        return goodsService.getCMSViewModelPageBySqlName(page, "get_coupons_goods_page", "get_coupons_goods_count",
                GoodsItemVO.class, condition.keySet().toArray(new String[0]), condition.values().toArray(new String[0]),
                new ArrayList(), filed, sort);
    }

}
